﻿using AutoMapper;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using Reporting.API.Application.Commands.Productionorders;
using Reporting.API.DTOs.ProductionorderPlanDTO;
using Reporting.API.Utils;
using Reporting.Domain;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.Productionorders;
using Reporting.Infrastructure.Interfaces.ProductionPlans;
using Reporting.Infrastructure.Interfaces.ProductTypes;

namespace Reporting.API.Application.CommandHandler.Productionorders
{
    public class GetProductionorderCommandHandler : IRequestHandler<GetProductionorderCommand, ApiResult<PagingResult<IList<ProductionorderPlanResponse>>>>
    {
        private readonly IProductionorderRepository _productionorderRepository;  //生产工单
        private readonly IProductTypeRepository _productTypeRepository;          //产品类型
        private readonly IProductionPlanRepository _productionPlanRepository;    //生产计划
        private readonly IMapper _mapper;
        private readonly ILogger<AddProductionorderCommandHandler> _logger;

        public GetProductionorderCommandHandler(ILogger<AddProductionorderCommandHandler> logger, IMapper mapper, IProductionorderRepository productionorderRepository, IProductionPlanRepository productionPlanRepository, IProductTypeRepository productTypeRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _productionorderRepository = productionorderRepository;
            _productionPlanRepository = productionPlanRepository;
            _productTypeRepository = productTypeRepository;
        }

        public async Task<ApiResult<PagingResult<IList<ProductionorderPlanResponse>>>> Handle(GetProductionorderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有生产工单
                var Productionorders = await _productionorderRepository.GetAllAsync();
                // 产品类型（外健）
                var Sourcetype = await _productTypeRepository.GetAllAsync();
                // 生产计划（外健）
                var ProductionPlans = await _productionPlanRepository.GetAllAsync();

                // 外健链接
                var result = from ProductionorderPlan in Productionorders
                             join ProductType in Sourcetype on ProductionorderPlan.ProductTypeID equals ProductType.ProductTypeID
                             join ProductionPlan in ProductionPlans on ProductionorderPlan.Productionplanid equals ProductionPlan.Productionplanid
                             select new ProductionorderPlanResponse
                             {
                                 Planname = ProductionPlan.Planname, //  生产计划名称
                                 Plannumber = ProductionPlan.Plannumber, //  生产计划编号
                                 ProductTypeName = ProductType.ProductTypeName, //  产品类型
                                 Productionorderid = ProductionorderPlan.Productionorderid,
                                 Workordernumber = ProductionorderPlan.Workordernumber,
                                 Workordername = ProductionorderPlan.Workordername,
                                 Workorderprogress = ProductionorderPlan.Workorderprogress,
                                 Productionplanid = ProductionorderPlan.Productionplanid,
                                 Productname = ProductionorderPlan.Productname,
                                 Productnumber = ProductionorderPlan.Productnumber,
                                 Specificationandmodel = ProductionorderPlan.Specificationandmodel,
                                 ProductTypeID = ProductionorderPlan.ProductTypeID,
                                 Productionorderunit = ProductionorderPlan.Productionorderunit,
                                 Requirementdate = ProductionorderPlan.Requirementdate,
                                 Plannedproduction = ProductionorderPlan.Plannedproduction,
                                 Actualproductionquantity = ProductionorderPlan.Actualproductionquantity,
                                 Scheduledstarttime = ProductionorderPlan.Scheduledstarttime,
                                 Plannedendtime = ProductionorderPlan.Plannedendtime,
                                 Actualstarttime = ProductionorderPlan.Actualstarttime,
                                 Actualendtime = ProductionorderPlan.Actualendtime,
                                 Productionorderstate = ProductionorderPlan.Productionorderstate
                             };

                //条件查询
                //任务编号、任务名称
                if (!string.IsNullOrEmpty(request.TaskNumberName))
                {
                    result = result.Where(x => x.Workordernumber == request.TaskNumberName || x.Workordername == request.TaskNumberName);
                }
                //计划编号、工单名称
                if (!string.IsNullOrEmpty(request.PlanNameAndNumber))
                {
                    result = result.Where(x => x.Plannumber == request.PlanNameAndNumber || x.Planname == request.PlanNameAndNumber);
                }
                //产品名称
                if (!string.IsNullOrEmpty(request.Productname))
                {
                    result = result.Where(x => x.Productname.Contains(request.Productname));
                }
                //状态
                if (request.Productionorderstate != null)
                {
                    result = result.Where(x => x.Productionorderstate == request.Productionorderstate);
                }


                // 当前页的数据
                var currentData = _mapper.Map<IList<ProductionorderPlanResponse>>(result.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize).ToList());

                // 分页
                var pagingResult = new PagingResult<IList<ProductionorderPlanResponse>>
                {
                    TotalCount = result.Count(),
                    TotalPage = Math.Ceiling(result.Count() / (double)request.PageSize),
                    Data = currentData
                };

                // 返回成功结果
                return ApiResult<PagingResult<IList<ProductionorderPlanResponse>>>.Success(pagingResult, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询失败");

                // 返回失败结果
                return ApiResult<PagingResult<IList<ProductionorderPlanResponse>>>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }

    }
}
